<template>
	<view class="content">
		<view class="top">
			<customHeader></customHeader>
		</view>
		<view class="center">
			<view class="search_content">
				<view class="item_search">
					<text class="title">订单日期:</text>
					<ruiDatePicker 
						fields="day" 
						style="flex: 1; border: 1rpx solid #ccc; height: 60rpx; width: 209rpx;"
						start="2018-01-01" 
						end="2040-12-30" 
						:value="dates" 
						@change="bindChange1">
					</ruiDatePicker>
					<text>—</text>
					<ruiDatePicker 
						fields="day" 
						style="flex: 1;border: 1rpx solid #ccc; height: 60rpx; width: 209rpx;"
						start="2018-01-01" 
						end="2040-12-30" 
						:value="datee" 
						@change="bindChange2">
					</ruiDatePicker>
				</view>
				<view class="item_search" style="margin: 0 20rpx;">
					<text class="title">客户名称:</text>
					<customDownSearch
						style="flex: 1; height: 30rpx; border: 1rpx solid #ccc; font-size: 30rpx;"
						:options="KehuListCom"
						:value="form.kehuName"
						v-model="form.kehuName"
						@changeInput="changeInput1"
						@input="handleInput1"
					></customDownSearch>
				</view>

				<view class="item_search">
					<text class="title">订单状态:</text>
					<customDownSearch
						style="flex: 1; height: 30rpx; border: 1rpx solid #ccc; font-size: 30rpx;"
						:options="stateListCom"
						:value="form.dingdanStatus"
						v-model="form.dingdanStatus"
						@changeInput="changeInput2"
						@input="handleInput2"
					></customDownSearch>
				</view>
			</view>

			<view class="search_content">
				<view class="item_search">
					<text class="title">经 手 人:</text>
					<customDownSearch
						style="flex: 1; height: 30rpx; border: 1rpx solid #ccc;font-size: 30rpx;"
						:options="kdPersonListCom"
						:value="form.yewuyuan"
						v-model="form.yewuyuan"
						@changeInput="changeInput3"
						@input="handleInput3"
					></customDownSearch>
				</view>

				<view class="item_search" style="margin: 0 20rpx;">
					<text class="title">订 单 号:</text>
					<!-- <customDownSearch
						style="flex: 1; height: 30rpx; border: 1rpx solid #ccc;font-size: 30rpx;"
						:options="ddhListCom"
						:value="form.danhao"
						v-model="form.danhao"
						@changeInput="changeInput4"
						@input="handleInput4"
					></customDownSearch> -->
					<input  
						style="flex: 1; height: 30rpx; border: 1rpx solid #ccc;font-size: 30rpx; padding: 10rpx 20rpx; width: 430rpx;"
						v-model="form.danhao"
					/>
				</view>
				<view class="item_search"></view>
			</view>

			<view class="search_btn">
				<u-button @click="handleDelete">删除</u-button>
				<u-button @click="handleSearch">查询</u-button>
			</view>

			<!-- 表头 -->
			<view class="table_content">
				<t-table style="width: 125%;">
					<t-tr style="position: sticky; top: 0; width: 100%; background: #fff; z-index: 9; " >
						<t-th style="flex:0 0 80upx;word-break: break-all;">
							<checkbox-group @change="changeAll">
								<checkbox value="selectAll" :checked="selectAll" />
							</checkbox-group>
						</t-th>
						<t-th style="flex:0 0 379upx;">订单号</t-th>
						<t-th style="flex:0 0 220upx;">订单日期</t-th>
						<t-th style="flex:0 0 151upx;">编号</t-th>
						<t-th>客户名称</t-th>

						<t-th>订单款数</t-th>
						<t-th>订单总数</t-th>
						<t-th>订单金额</t-th>

						<t-th>经手人</t-th>
						<t-th>订单状态</t-th>
						<!-- <t-th>排产状态</t-th>
						<t-th>发货状态</t-th> -->

						<t-th>完工数量</t-th>
						<t-th>发货数量</t-th>
						<t-th>发货金额</t-th>
					</t-tr>
					<view style="flex: 1; overflow: auto;" v-for="(item, index) in data" :key="index" @click="handleEnter(item)">
						<t-tr>
							<t-td style="flex:0 0 80upx;word-break: break-all;">
								<checkbox-group @change.stop="changeBox($event, item, index)">
									<checkbox value="check" :checked="item.check" />
								</checkbox-group>
							</t-td>
							<t-td style="flex:0 0 379upx;">{{ item.no }}</t-td>
							<t-td  style="flex:0 0 220upx;">{{ item.date }}</t-td>
							<t-td  style="flex:0 0 151upx;">
								<view style="word-wrap: break-word; width: 151upx;">{{ item.customer_no}}</view>
							</t-td>
							<t-td>{{ item.customer_name }}</t-td>

							<t-td>{{ item.skus }}</t-td>
							<t-td>{{ item.total }}</t-td>
							<t-td>{{ item.amount }}</t-td>

							<t-td>{{ item.bizman_name }}</t-td>
							<t-td>{{ item.state }}</t-td>
							<!-- <t-td>{{ item.state }}</t-td>
							<t-td>{{ item.state }}</t-td> -->

							<t-td>{{ item.comp_qty }}</t-td>
							<t-td>{{ item.disp_qty }}</t-td>
							<t-td>{{ item.disp_amount }}</t-td>
						</t-tr>
					</view>

					<t-tr class="none">
						<t-th class="none" style="flex:0 0 80upx;word-break: break-all;">合计:</t-th>
						<t-th class="none" style="flex:0 0 379upx;"></t-th>
						<t-th  style="flex:0 0 220upx;" class="none"></t-th>
						<t-th style="flex:0 0 151upx;" class="none"></t-th>
						<t-th class="none"></t-th>
						<t-th class="none" style="color: red;">{{ sumCom }}</t-th>
						<t-th class="none" style="color: red;">{{ sumAllCom }}</t-th>
						<t-th class="none" style="color: red;">{{ amountCom.toFixed(2) }}</t-th>
						<t-th class="none"></t-th>
						<t-th class="none"></t-th>
						<!-- <t-th class="none"></t-th>
						<t-th class="none"></t-th> -->
						<t-th class="none" style="color: red;">{{ completionCom }}</t-th>
						<t-th class="none" style="color: red;">{{ fhslCom }}</t-th>
						<t-th class="none" style="color: red;">{{ shjeCom.toFixed(2) }}</t-th>
					</t-tr>
				</t-table>
			</view>

			<view class="bottom_content">
				<view>
					<myPagination 
						:key="'dingdanTable-' + pageIndex"
						style="height: 80rpx;"
						:totalPage="totalCount" 
						:pageIndex="pageIndex" 
						:changeCallback="parentCallback">
					</myPagination>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
import { mapState } from 'vuex'

import customHeader from '@/components/custom-header/custom-header.vue'
import ruiDatePicker from '@/components/rattenking-dtpicker/rattenking-dtpicker.vue'
import customDownSearch from '@/components/custom-downSearch/custom-downSearch.vue'
import customPagination from '@/components/custom-pagination/custom-pagination.vue'
import myPagination from '@/components/my-pagination/my-pagination.vue'
import tTable from '@/components/t-table/t-table.vue'
import tTh from '@/components/t-table/t-th.vue'
import tTr from '@/components/t-table/t-tr.vue'
import tTd from '@/components/t-table/t-td.vue'

import { tableDetail, dingdState, dingdOrder, deleteDd } from "@/api/modules/table.js"
import { getKehuList, getKdPersonList, getGradeList, getAreaList } from '@/api/modules/select.js'
const { currentdate, beforedate } = getNowFormatDate()
	var timer_s = beforedate
	var timer_e = currentdate
	function getNowFormatDate() {
		var date = new Date();
		var seperator1 = "-";
		var seperator2 = ":";
		var month = date.getMonth() + 1;  // 当前月
		var month2 = month - 2;  // 当前月往前推2个月
		var strDate = date.getDate();  // 当前日
		
		// 如果月份小于10，前面加0
		if (month >= 1 && month <= 9) {
			month = "0" + month;
		}
		
		// 如果月份2小于10，前面加0
		if (month2 < 1) {
			month2 += 12;  // 如果月份为负数，回到上一年
			date.setFullYear(date.getFullYear() - 1);  // 年份减1
		}
		if (month2 >= 1 && month2 <= 9) {
			month2 = "0" + month2;
		}

		// 如果日期小于10，前面加0
		if (strDate >= 1 && strDate <= 9) {
			strDate = "0" + strDate;
		}

		var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
		var beforedate = date.getFullYear() + seperator1 + month2 + seperator1 + strDate;
		return {
			currentdate,
			beforedate
		};
	}

	function debounce  (func, wait) {  
		let timeout;  
		return function() {  
			const context = this;  
			const args = arguments;  
			if (timeout) clearTimeout(timeout);  
			timeout = setTimeout(function() {  
			func.apply(context, args);  
			}, wait);  
		};  
	}

	export default {
		components:{
			customHeader, 
			ruiDatePicker,
			customDownSearch,
			customPagination,
			myPagination,
			tTable,
		    tTh,
		    tTr,
		    tTd,
		},
		data() {
			return {
				dates: timer_s,
				datee: timer_e,
				form: {
					kehuName: '', // 客户名称
					dingdanStatus: '', // 订单状态
					yewuyuan: '', // 业务员
					danhao: '', // 订单号
				},
				selectAll: false, // 全选按钮
				data: [],

				kehuList: [], // 客户名称
				dingdStateList: [], // 订单状态
				pcStateList: [], // 排产状态
				fhStateList: [], // 发货状态
				yewuSelectList: [], // 业务员
				orderList: [], // 订单号
				timingNum: 1, // 判断 要不要跳转
				pageSize: 10, // 下单页数
				pageIndex: 1, // 当前页数
				totalCount: 0, // 应该有多少条数据
				stateMap: {  // 订单状态
					'wmssoy_01': '待提交',
					'wmssoy_02': '待审核',
					'wmssoy_03': '待排产',
					'wmssoy_04': '已排产',
					'wmssoy_08': '待发货',
					'wmssoy_09': '已出库',
					'wmssoy_19': '已发货',
					'wmssoy_99': '已取消',
				},
				scrollTop: 0,

				debouncedGetKehu: debounce(this.getKehu, 500),  // 客户名称 防抖
				debouncedKdPerson: debounce(this.getKdPerson, 500),  // 开单业务 防抖
				debouncedState: debounce(this._dingdState, 500),  // 状态 防抖
				active_menu_id: '', // 当前选中的菜单
			}
		},
		onLoad(r) {
			this.active_menu_id = r.id
			let param = {
				paging: {
					pageIndex: 1,
					pageSize: this.pageSize,
				}, 
				query: {
					state: '', // 订单状态
					customer_id: '', // 客户订单
					bizman_id: '', // 业务员
					active_menu_id: this.active_menu_id, // 菜单id
					startdate: this.dates, 
					enddate: this.datee,
					search: '', //查询指定产品订单
				}
			}
			this._tableDetail(param);
			this.getKehu(); // 客户名称
			this._dingdState(); // 获取订单状态
			this.getKdPerson(); // 开单业务员
			// this._pcState(); // 获取排产状态
			// this._fhState(); // 获取发货状态
			// this._dingdOrder(); // 订单号
		},
		
		computed: {
			...mapState(['sideList', 'indexList']),
			KehuListCom(){
				let arr = [];
				 (this.kehuList || []).forEach(i => {
					arr.push(i.name)
				 })
				 return arr
			},
			stateListCom(){
				let arr = [];
				 (this.dingdStateList || []).forEach(i => {
					arr.push(i.text)
				 })
				 return arr
			},
			kdPersonListCom(){
				let arr = [];
				 (this.yewuSelectList || []).forEach(i => {
					arr.push(i.name)
				 })
				 return arr
			},
			ddhListCom(){
				let arr = [];
				 (this.orderList || []).forEach(i => {
					arr.push(i.dh)
				 })
				 return arr
			},
			completionCom() {
				return this.data.reduce((a, b) => a += b.comp_qty, 0)
			},
			fhslCom() {
				return this.data.reduce((a, b) => a += b.disp_qty, 0)
			},
			shjeCom() {
				return this.data.reduce((a, b) => a += b.disp_amount, 0)
			},
			sumCom( ) {
				return this.data.reduce((a, b) => a += b.skus, 0)
			},
			sumAllCom( ) {
				return this.data.reduce((a, b) => a += b.total, 0)
			},
			amountCom( ) {
				let sumA =  this.data.reduce((a, b) =>  a +  parseInt(b.amount * 10000), 0)
				return sumA / 10000
			},
		},
		watch: {
			data: {
				handler(newVal, oldVal) {
					if (newVal.length == 0) {
						this.selectAll = false
						return
					}
					if (newVal.every(i => i.check)) {
						this.selectAll = true
					} else {
						this.selectAll = false
					}
				},
				immediate: true,
				deep: true
			}
		},
		methods: {
			reload() { // 上一个页面回退时候，页面刷新
				let param = {
					paging: {
						pageIndex: this.pageIndex,
						pageSize: this.pageSize,
					}, 
					query: {
						state: this.dingdStateList.filter(i => i.text == this.form.dingdanStatus)[0]?.no, // 订单状态
						customer_id: this.kehuList.filter(i => i.name == this.form.kehuName)[0]?.id, // 客户订单
						bizman_id: this.yewuSelectList.filter(i => i.name == this.form.yewuyuan)[0]?.id, // 业务员
						startdate: this.dates, 
						enddate: this.datee,
						search: this.form.danhao, //查询指定产品订单
						active_menu_id: this.active_menu_id, // 菜单id
					}
				}
				this._tableDetail(param);
			},
			parentCallback(pages) {
				this.pageIndex = pages
				this.scrollTop = 0
				let param = {
					paging: {
						pageIndex: pages,
						pageSize: this.pageSize,
					}, 
					query: {
						state: this.dingdStateList.filter(i => i.text == this.form.dingdanStatus)[0]?.no, // 订单状态
						customer_id: this.kehuList.filter(i => i.name == this.form.kehuName)[0]?.id, // 客户订单
						bizman_id: this.yewuSelectList.filter(i => i.name == this.form.yewuyuan)[0]?.id, // 业务员
						startdate: this.dates, 
						enddate: this.datee,
						search: this.form.danhao, //查询指定产品订单
						active_menu_id: this.active_menu_id, // 菜单id
					}
				}
				this._tableDetail(param);
			},
			handleSearch() {
				let param = {
					paging: {
						pageIndex: 1,
						pageSize: this.pageSize,
					}, 
					query: {
						state: this.dingdStateList.filter(i => i.text == this.form.dingdanStatus)[0]?.no, // 订单状态
						customer_id: this.kehuList.filter(i => i.name == this.form.kehuName)[0]?.id, // 客户订单
						bizman_id: this.yewuSelectList.filter(i => i.name == this.form.yewuyuan)[0]?.id, // 业务员
						startdate: this.dates, 
						enddate: this.datee,
						search: this.form.danhao, //查询指定产品订单
						active_menu_id: this.active_menu_id, // 菜单id
					}
				}

				this.pageIndex = 1
				this._tableDetail(param);
			},
			async handleDelete() {
				if (!this.data.filter(i => i.check).length ) {
					uni.showToast({
						title: '请选择要删除的订单!',
						duration: 2000,
						icon: 'none'
					});
					return
				}
				let param = JSON.parse(JSON.stringify(this.data)).filter(i => i.check).map(i => ({id: i.id, no: i.no}))
				const res = await deleteDd(JSON.stringify(param))
				// console.log('=== 删除', res)
				const { data: { status, message } } = res || {}

				if (status == 'success') {
					uni.showToast({
						title: '删除成功!',
						duration: 2000,
						icon: 'none'
					});
					this.data = JSON.parse(JSON.stringify(this.data)).filter(i => !i.check)
				} else if (status === 'fail') {
					uni.showToast({
						title: message,
						duration: 2000,
						icon: 'none'
					});
				} 
			},
			
			changeAll() { // 全选
				this.selectAll = !this.selectAll
				console.log('== 全选')
				if (this.selectAll) {
					this.data = JSON.parse(JSON.stringify(this.data)).map((i, j) => ({...i, check: true}))
				} else if (!this.selectAll) {
					this.data = JSON.parse(JSON.stringify(this.data)).map((i, j) => ({...i, check: false}))
				}
			},
			changeBox(e, item, index) { // 单选
				this.data = JSON.parse(JSON.stringify(this.data)).map((i, j) => ({...i, check: j === index ? !i.check : i.check}))
				e.stopPropagation()
				e.preventDefault()
				this.timingNum = 0
			},
			handleEnter(param) {
				this.timingNum++
				if (this.timingNum === 1) {
					return
				}
				uni.navigateTo({
						url: `./ddDetails?paramId=${param.id}`
				});
			},
			changeInput1(opt) {
				this.form.kehuName = opt
			},
			handleInput1(opt) {
				this.form.kehuName = opt
				this.debouncedGetKehu(opt)
			},

			changeInput2(opt) {
				this.form.dingdanStatus = opt
			},
			handleInput2(opt) {
				this.form.dingdanStatus = opt
				this.debouncedState(opt)
			},

			changeInput3(opt) {
				this.form.yewuyuan = opt
			},
			handleInput3(opt) {
				this.form.yewuyuan = opt
				this.debouncedKdPerson(opt)
			},

			changeInput4(opt) {
				this.form.danhao = opt
			},
			handleInput4(opt) {
				this.form.danhao = opt
			},

			bindChange1(value) { // 日期选择
				this.dates = value;
			},
			bindChange2(value) { // 日期选择
				this.datee = value;
			},
			async _tableDetail(param) {
				
				// const res = await tableDetail({data: JSON.stringify(param), pageSize: this.pageSize, pageIndex: this.pageIndex})
				const res = await tableDetail(JSON.stringify(param))
				// console.log('== res 订单列表', res)

				const { data: { data, status, message } } = res || {}

				if (status == 'success') {
					if (!data.sorders.length) {
						uni.showToast({
							title: '暂无数据!',
							duration: 2000,
							icon: 'none'
						});
					}
					this.totalCount = Math.ceil(data.paging.total / this.pageSize)
					this.data = (data.sorders || []).map(i => ({ 
						...i, 
						check: false, 
						// state: this.stateMap[i.state],  
						state: this.dingdStateList.find(j => j.no == i.state)?.text || '',  
					}))
				} else if (status === 'fail') {
					uni.showToast({
						title: message,
						duration: 2000,
						icon: 'none'
					});
				} 
			},
			async getKehu(str='') { // 客户信息
				let param = {
					paging: {
						pageIndex: 1,
						pageSize: 200,
					},
					query: {
						type_nos: ["customer"],
						valid: true,
						search: str, // 搜索字段
					},
				}
				const res = await getKehuList(JSON.stringify(param))
				const { data: { data } } = res || {}
				// console.log('== 客户信息', res)
				this.kehuList = (data.companys ? data.companys : [])
			},

			async _dingdState(str = '') { // 订单状态
				let param = {
					paging: {
						pageIndex: 1,
						pageSize: 200,
					},
					query: {
						dictype_no: "wms_sorder_state",
						search: str, // 搜索字段
						valid: 'true',
					},
				}
				const res = await dingdState(JSON.stringify(param)) 
				const { data:{ data } } = res || {}
				this.dingdStateList = (data.dictionaries ? data.dictionaries : [])
				// console.log('== 状态', res.data)
			},
			async _pcState(str = '') { // 排产状态
				let param = {
					paging: {
						pageIndex: 1,
						pageSize: 200,
					},
					query: {
						dictype_no: "wms_pc_state",
						search: str, // 搜索字段
						valid: 'true',
					},
				}
				const res = await dingdState(JSON.stringify(param)) 
				const { data:{ data } } = res || {}
				this.pcStateList = (data.dictionaries ? data.dictionaries : [])
			},
			async _fhState(str = '') { // 发货状态
				let param = {
					paging: {
						pageIndex: 1,
						pageSize: 200,
					},
					query: {
						dictype_no: "wms_pc_state",
						search: str, // 搜索字段
						valid: 'true',
					},
				}
				const res = await dingdState(JSON.stringify(param)) 
				const { data:{ data } } = res || {}
				this.fhStateList = (data.dictionaries ? data.dictionaries : [])
			},
			async getKdPerson(str = '') { // 开单业务
				let param = {
					paging: {
						pageIndex: 1,
						pageSize: 200,
					},
					query: {
						role_type_no: "wms",
						refcompany: false,
						valid: true,
						search: str, // 搜索字段
					},
				}
				const res = await getKdPersonList(JSON.stringify(param))
				const { data: { data } } = res || {}
				// console.log('== 开单业务', res)
				this.yewuSelectList = (data.users ? data.users : [])
			},
			async _dingdOrder() {
				const res = await dingdOrder({ pagesize: 100000000000, pageindex: 1 })
				const { data } = res || {}
				// console.log('== 订单号', data)
				this.orderList = (data? data : [])
			},
		}
	}
</script>

<style lang="less" scoped>
.content {
	height: 100vh;
	display: flex;
	flex-direction: column;
	.top {
		position: fixed;
		width: 100%;
		z-index: 12;
	}

	.center {
		padding: 0 40rpx;
		padding-top: 158rpx;
		flex: 1;
		display: flex;
		flex-direction: column;
		overflow: auto;

		/* 隐藏滚动条 
		::-webkit-scrollbar {
			display: none;
		}
		-ms-overflow-style: none;
		scrollbar-width: none;
		*/

		.search_content {
			display: flex;
			align-items: center;
			// justify-content: space-between;
			margin-top: 30rpx;
			width: 100%;
			.item_search {
				display: flex;
				align-items: center;
				height: 60rpx;
				width: 33%;

				.title {
					font-size: 40rpx;
					font-weight: 700;
					width: 200rpx;
				}
			}
		}

		.search_btn {
			display: flex;
			justify-content: space-between;
			margin: 30rpx;

			button {
				width: 360rpx;
				color: #fff;
				margin: 0;
				font-size: 50rpx;
			}

			button:nth-child(1) {
				background: red;
			}
			button:nth-child(2) {
				background: #f59a23;
			}
		}
		
		.table_content {
			flex: 1;
			width: 100%;
			overflow: auto;
		}

		.bottom_content {
			margin: 20rpx 0;
			font-size: 34rpx;

			.none {
				border: none;
			}
		}
	}
}
</style>
